package com.brooks.demo;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Semaphore 信号灯
 * @Author mihutu
 * @Date 2020/10/19 10:05
 * @Version 1.0
 */
public class DemoSemaphore {
    public static void main(String[] args) {
        //允许几个线程同时执行
        Semaphore semaphore = new Semaphore(1);
        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("t1 start====");
                TimeUnit.SECONDS.sleep(2);
                System.out.println("t1 end====");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();
        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("t2 start====");
                TimeUnit.SECONDS.sleep(2);
                System.out.println("t2 end====");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();
    }
}
